package com.wayne.blog.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wayne.blog.entity.ArticleLike;
import com.wayne.blog.mapper.ArticleLikeMapper;
import com.wayne.blog.service.ArticleLikeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 文章喜欢服务实现类
 */
@Service
public class ArticleLikeServiceImpl extends ServiceImpl<ArticleLikeMapper, ArticleLike> implements ArticleLikeService {

    @Override
    @Transactional
    public void likeArticle(Long articleId) {
        // 获取当前登录用户ID
        Long userId = StpUtil.getLoginIdAsLong();
        
        // 检查是否已经喜欢
        if (isLiked(articleId)) {
            return;
        }

        // 创建喜欢记录
        ArticleLike articleLike = new ArticleLike();
        articleLike.setArticleId(articleId);
        articleLike.setUserId(userId);
        save(articleLike);
    }

    @Override
    @Transactional
    public void unlikeArticle(Long articleId) {
        // 获取当前登录用户ID
        Long userId = StpUtil.getLoginIdAsLong();

        // 删除喜欢记录
        remove(new LambdaQueryWrapper<ArticleLike>()
                .eq(ArticleLike::getArticleId, articleId)
                .eq(ArticleLike::getUserId, userId));
    }

    @Override
    public boolean isLiked(Long articleId) {
        // 获取当前登录用户ID
        Long userId = StpUtil.getLoginIdAsLong();
        
        // 查询是否喜欢
        return baseMapper.checkLike(articleId, userId) > 0;
    }

    @Override
    public int getLikeCount(Long articleId) {
        return baseMapper.getLikeCount(articleId);
    }
} 